package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.SetmealDao;
import com.itheima.dao.SetmealDishDao;
import com.itheima.pojo.DishFlavor;
import com.itheima.pojo.DishSet;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.SetmealService;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishDao setmealDishDao;

    //添加
    @Override
    public void Add(DishSet set) {
        save(set);

        extracted(set);
    }

    @Override
    public void updateBI(DishSet set) {
        //修改
        updateById(set);

        List<SetmealDish> dishes = set.getSetmealDishes();
        if(dishes!=null){
            for (SetmealDish dish : dishes) {

                QueryWrapper<SetmealDish> wrapper = new QueryWrapper<>();
                wrapper.eq("setmeal_id", set.getId());
                setmealDishDao.delete(wrapper);
            }
        }
        //重新添加
        extracted(set);
    }

    private void extracted(DishSet set) {

        if (set.getSetmealDishes() != null) {

            for (SetmealDish setmealDish : set.getSetmealDishes()) {

                setmealDish.setSetmealId(set.getId());

                setmealDishDao.insert(setmealDish);
            }
        }
    }
}
